#include "sqldatabase.h"

#include "dbtablemanager.h"
#include "dataoperate.h"

SqlDatabase::SqlDatabase(QObject *parent)
    : QObject(parent), m_DBTableManager(NULL)
{
}

SqlDatabase::~SqlDatabase()
{
}

bool SqlDatabase::InitDataBase(const QString &host, const int &port, const QString &user, const QString &pass, const QString &DBName)
{
    qInfo() << "SqlDatabase CreateConnection";
    m_QDataBase = QSqlDatabase::addDatabase("QMYSQL", user + "@" + host);
    m_QDataBase.setHostName(host);
    m_QDataBase.setPort(port);
    m_QDataBase.setDatabaseName(DBName);
    m_QDataBase.setUserName(user);
    m_QDataBase.setPassword(pass);

    // 打开失败，则创建新的数据库
    if (!m_QDataBase.open())
    {
        QSqlError error = m_QDataBase.lastError();
        qWarning() << "SqlDatabase::createConnection Error:" << error.text();
        return false;
    }
    qInfo() << "SqlDatabase::createConnection : InitDataBase success";
    return true;
}

bool SqlDatabase::CreateSqlDataBase(const QString& createSqlPath)
{
    qInfo() << "SqlDatabase::CreateSqlDatabase:Start CreateSqlDatabase!";
    bool iRet = true;
    QFile qfile(createSqlPath);
    if (!qfile.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        qWarning() << createSqlPath << "open failed:" << qfile.errorString();
        return false;
    }
    QString qstr_file_data = qfile.readAll();
    QSqlQuery qsql(m_QDataBase);
    QStringList qstrlist_sql = qstr_file_data.split(";");
    for (int i = 0; i < qstrlist_sql.size() - 1; i++)
    {
        QString qstr_sql_part = qstrlist_sql.at(i).toUtf8();
        bool sql_result = qsql.exec(qstr_sql_part);
        if (!sql_result)
        {
            qWarning() << "SqlDatabase::CreateSqlDatabase:" << qsql.lastError().text();
            iRet = false;
            break;
        }
    }
    return iRet;
}

bool SqlDatabase::InitDBTables()
{
    m_DBTableManager = new DBTableManager(this);
    m_DBTableManager->InitAllTable(m_QDataBase.connectionName());
    return true;
}

bool SqlDatabase::DisDatabaseConnect()
{
    m_QDataBase.close();
    return true;
}

bool SqlDatabase::SqlBackup(const QString& /*path*/)
{
    return true;
}

bool SqlDatabase::SqlReduction(const QString& /*path*/)
{
    return true;
}

bool SqlDatabase::isValid()
{
    return m_QDataBase.isOpen();
}

bool SqlDatabase::DataBaseOperate(DataOperate &DataOpera)
{
    return (m_DBTableManager && m_DBTableManager->DataBaseOperate(DataOpera));
}

bool SqlDatabase::IsUpdate(void)
{
    return false;
}

bool SqlDatabase::UpataSqlDatabase(const QString& /*upateSqlPath*/)
{
    return false;
}
